import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:ui';

class AddImageWaterUtil {
  static Future<File> addImageWaterUnit8List(Uint8List bytes, String filePath,
      String text, TextStyle textStyle) async {
    // 2. 解码原始图片
    final codec = await ui.instantiateImageCodec(bytes);
    final frame = await codec.getNextFrame();
    final image = frame.image;

    // 3. 创建绘图画布
    final recorder = ui.PictureRecorder();
    final canvas = Canvas(recorder,
        Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()));

    // 4. 绘制原始图片
    canvas.drawImage(image, Offset.zero, Paint());

    // 5. 配置水印样式
    // final textStyle = ui.TextStyle(
    //     color: ui.Color.fromARGB(70, 0, 0, 0), // 半透明白色
    //     fontSize: 22,
    //     fontFamily: 'Roboto' // 确保字体可用
    // );

    // 6. 创建文本画笔
    final paragraphBuilder = ui.ParagraphBuilder(ui.ParagraphStyle())
      ..pushStyle(textStyle)
      ..addText(text);

    final paragraph = paragraphBuilder.build()
      ..layout(ui.ParagraphConstraints(width: double.infinity));

    // 7. 计算水印平铺参数
    final textWidth = paragraph.minIntrinsicWidth;
    final textHeight = paragraph.height;
    final diagonal = textWidth * 1.6;
    final stepX = diagonal * 1;
    final stepY = diagonal * 0.5;
    // 8. 应用画布变换
    canvas.save();
    final centerX = image.width / 2;
    final centerY = image.height / 2;
    canvas.translate(centerX, centerY);
    canvas.rotate(-45 * (3.1415927 / 180)); // 旋转45度
    canvas.translate(-centerX, -centerY);

    // 9. 平铺绘制水印
    for (double x = -image.width.toDouble(); x < image.width * 2; x += stepX) {
      for (double y = -image.height.toDouble();
          y < image.height * 2;
          y += stepY) {
        canvas.drawParagraph(paragraph, Offset(x, y));
      }
    }
    canvas.restore();

    // 10. 生成最终图片
    final picture = recorder.endRecording();
    final watermarkedImage = await picture.toImage(image.width, image.height);
    final byteData =
        await watermarkedImage.toByteData(format: ui.ImageByteFormat.png);
    final watermarkedBytes = byteData!.buffer.asUint8List();
    // 将压缩后的图片保存到临时文件
    File compressedFile = File("${filePath}_compressed.jpg")
      ..writeAsBytesSync(watermarkedBytes!);
    return compressedFile;
  }

  static Future<File> addImageWaterFile(
      File file, String text, TextStyle textStyle) async {
    return addImageWaterUnit8List(
        await file.readAsBytes(), file.absolute.path, text, textStyle);
  }
  static Future<File> addTextWatermarkAtPositionFile(
      File file, String text, TextStyle textStyle,double x,double y) async {
    return addTextWatermarkAtPosition(
        await file.readAsBytes(), file.absolute.path, text, textStyle,x,y);
  }

  /// 从 Uint8List 添加文字水印到指定坐标 (x, y)
  static Future<File> addTextWatermarkAtPosition(
      Uint8List bytes,
      String filePath,
      String text,
      TextStyle textStyle,
      double x,
      double y) async {
    // 1. 解码原始图片
    final codec = await ui.instantiateImageCodec(bytes);
    final frame = await codec.getNextFrame();
    final image = frame.image;

    // 2. 创建绘图画布
    final recorder = ui.PictureRecorder();
    final canvas = Canvas(recorder,
        Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()));

    // 3. 绘制原始图片
    canvas.drawImage(image, Offset.zero, Paint());

    // 4. 创建文本画笔
    final paragraphBuilder = ui.ParagraphBuilder(ui.ParagraphStyle())
      ..pushStyle(textStyle)
      ..addText(text);

    final paragraph = paragraphBuilder.build()
      ..layout(ui.ParagraphConstraints(width: double.infinity));

    // 5. 在指定坐标绘制水印
    canvas.drawParagraph(paragraph, Offset(x, y));

    // 6. 生成最终图片
    final picture = recorder.endRecording();
    final watermarkedImage = await picture.toImage(image.width, image.height);
    final byteData =
        await watermarkedImage.toByteData(format: ui.ImageByteFormat.png);
    final watermarkedBytes = byteData!.buffer.asUint8List();

    // 保存到文件
  int num=  Random().nextInt(10000);
    File compressedFile = File("${filePath}_wzcompressed${num}.jpg")
      ..writeAsBytesSync(watermarkedBytes);
    return compressedFile;
  }
}
